import { NextRequest, NextResponse } from 'next/server';
import { getMonitoringManager, isServicesInitialized } from '@/lib/services-init';
import { createModuleLogger } from '@/utils/logger';

const logger = createModuleLogger('health-check');

export async function GET(request: NextRequest) {
  try {
    const servicesReady = isServicesInitialized();
    const monitoringManager = getMonitoringManager();
    
    let monitoringStatus = null;
    let isMonitoringHealthy = false;
    
    if (monitoringManager) {
      monitoringStatus = monitoringManager.getAllStatus();
      isMonitoringHealthy = monitoringStatus.activeCount > 0;
    }

    const overallHealth = servicesReady && (monitoringManager !== null);
    const status = overallHealth ? 'healthy' : 'starting';

    const healthData = {
      status,
      timestamp: new Date().toISOString(),
      services: {
        initialized: servicesReady,
        monitoring: {
          available: monitoringManager !== null,
          active: isMonitoringHealthy,
          activeChains: monitoringStatus?.activeCount || 0,
          totalChains: monitoringStatus?.monitorCount || 0,
          details: monitoringStatus?.chains || {}
        }
      },
      environment: {
        nodeEnv: process.env.NODE_ENV,
        autoStartEnabled: process.env.AUTO_START_MONITORING === 'true'
      },
      uptime: process.uptime(),
      memory: process.memoryUsage()
    };

    // 根据健康状态返回适当的HTTP状态码
    const httpStatus = overallHealth ? 200 : 503;
    
    return NextResponse.json(healthData, { status: httpStatus });
    
  } catch (error) {
    logger.error('❌ 健康检查失败:', error);
    return NextResponse.json(
      {
        status: 'error',
        timestamp: new Date().toISOString(),
        error: '健康检查失败',
        details: error instanceof Error ? error.message : String(error)
      },
      { status: 500 }
    );
  }
}

// 支持HEAD请求用于简单的存活检查
export async function HEAD(request: NextRequest) {
  try {
    const servicesReady = isServicesInitialized();
    const monitoringManager = getMonitoringManager();
    const overallHealth = servicesReady && (monitoringManager !== null);
    
    return new NextResponse(null, { 
      status: overallHealth ? 200 : 503,
      headers: {
        'X-Health-Status': overallHealth ? 'healthy' : 'starting',
        'X-Services-Ready': servicesReady.toString(),
        'X-Monitoring-Available': (monitoringManager !== null).toString()
      }
    });
  } catch (error) {
    return new NextResponse(null, { status: 500 });
  }
} 